import {Menu} from "./expressExt/Menu";
//初始化
Menu.init(__dirname);

import * as https from 'https';
import * as fs from "fs";
import * as express from 'express';
import * as http from 'http';
import * as morgan from 'morgan';
import * as bodyParser from 'body-parser';
import * as  methodOverride from 'method-override';
import * as compression from 'compression';
import * as cookieParser from 'cookie-parser';
import * as path  from 'path';
import * as net from 'net';
import {exp} from "./expressExt/exp";
import {Log} from "./expressExt/Log";
import {ExpressExt} from "./expressExt/ExpressExt";
import {mysqlModel} from "./configExt/mysqlModel";
import {Config} from "./configExt/Config";
import {Tasks} from "./configExt/Tasks";
import {HotReload} from "./expressExt/HotReload";
import {Request} from "express";
import {Response} from "express";
import {rpc} from "./rpc/rpc";
import {RpcServer} from "./expressExt/rpc/RpcServer";
import {LogicCheck} from "./logic/LogicCheck";
import {GenCfg} from "./configExt/GenCfg";
import {RpcConfig} from "./configExt/RpcConfig";


/**
 * enableHTML==true表示为测试环境
 */
if (Config.enableHTML) {

    //生成接口文档
    ExpressExt.routeUrl = GenCfg.start

} else {//生产环境
    //禁用控制台输出
    Log.enableConsole = false;
}

/**
 * 启用定时任务
 */
Tasks.startAll();

var app = express();

//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');

//日志
app.use(morgan('short', {
    stream: {
        write: function (str) {
            Log.write(str, null, Log.getCutFile("access.log"));
        }
    },
}));

app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());
app.use(methodOverride());

//启用压缩
app.use(compression());

//
//启用cookie
app.use(cookieParser("dsqikmnfhtlp"));

// app.use(app.router);

/**
 * 未处理的Promise Rejection
 */
process.on('unhandledRejection', function (error, promise) {
    Log.write("unhandled Rejection:", error);
});


/**
 * 生成mysql model
 */
if (Config.enableMysqlModel)
    mysqlModel.start();

/**
 * 加载路由文件
 */
ExpressExt.loadRoutes(app, [
    {
        menu: "routes",
        onCheckData: LogicCheck.getOnCheckData(void 0, true),
        onCatch: LogicCheck.getOncatch(true),
    },
    {
        menu: "api",
        onCheckData: LogicCheck.getOnCheckData(void 0),
        onCatch: LogicCheck.getOncatch()
    },
]);

/**
 * 静态资源
 */
app.use(express.static(path.join(__dirname, 'public')));


/**
 * 404路由
 */
app.use(function responser(req: Request, resp: Response, next: () => void) {
    resp.status(404);
    resp.end('404, Page Not Found!');
});


//错误处理
function errorHandler(err, req: Request, res: Response, next: (err: any) => void): any {
    Log.write(req.url + " " + req.ip + " errorHandler: " + JSON.stringify(req[exp.reqFormDat] || ExpressExt.setReqParas(req)), err);
    res.status(500);
    res.end(exp.netErr);
}

app.use(errorHandler);


/**
 * 启动http服务
 */
http.createServer(app).listen(RpcConfig.rpcServer.portHttp, function () {
    console.log('Express server listening on port ' + RpcConfig.rpcServer.portHttp);
}).on('connection', function (socket: net.Socket) {
    //console.log("A new connection was made by a client.");
    //设置客户端链接超时值为5分钟
    socket.setTimeout(5 * 60 * 1000);
});

//启动https服务
// var options = {
//     key: fs.readFileSync(Menu.root + '/configExt/keys/server.key'),
//     cert: fs.readFileSync(Menu.root + '/configExt/keys/server.crt'),
//     ca: fs.readFileSync(Menu.root + '/configExt/keys/1_root_bundle.crt'),
// };
//
// https.createServer(options, app).listen(Config.rpcServer.portHttps, function () {
//     console.log('Express server HTTPS listening on port ' + Config.rpcServer.portHttps);
// }).on('connection', function (socket: net.Socket) {
//     //console.log("A new connection was made by a client.");
//     socket.setTimeout(10 * 60 * 1000);
// });

if (Config.enableHTML) {
    //内存缓存
    RpcServer.serverStart(RpcConfig.rpcServer.portRpc, rpc);

    /**
     * 指定热更新目录
     */
    HotReload.start([
        Menu.root + "/logic",
        Menu.root + "/models",
        Menu.root + "/modReq",
        Menu.root + "/views",
    ]);
}